var groups = new Array();

function initializeComposeList()
{
    groups[0] = new Array(); /* "To" */
    groups[1] = new Array(); /* "CC" */
    groups[2] = new Array(); /* "BCC" */

    compose = document.getElementById( 'compose' );
    if ( compose ) {
        compose.href = '';
        compose.title = '';
        compose.style.display = 'none';
    }
}
initializeComposeList();

function toggle( group, address, id )
{

    compose = document.getElementById( 'compose' );
    button = document.getElementById( group + '_' + id );
    mailto = 'mailto:';
    tooltip = '';
    found = null;

    // Toggle the button
    if ( button.getAttribute( 'class' ).match( 'toggle_not_selected' )) {
        button.className = 'toggle_selected';
    } else if ( button.getAttribute( 'class' ).match( 'toggle_selected' )) {
        button.className = 'toggle_not_selected';
    }

    // Search for the address in the group
    for ( i in groups[ group ] ) {
        if ( groups[ group ][ i ].match( address )) {
            found = i;        
        }
    }

    // Add or remove an address
    if ( found == null ) {
        groups[ group ].push( address );
    } else {
        groups[ group ].splice( found, 1 ); 
    }

    // Generate the mailto link
    if ( groups[ 0 ].length > 0 ) {
        mailto = mailto + groups[ 0 ].join( ',' );
        tooltip = tooltip + 'To: ' + groups[ 0 ].length + ' ';
    }
    if ( groups[ 1 ].length > 0 ) {
        mailto = mailto + '?CC=' + groups[ 1 ].join( ',' );
        tooltip = tooltip + 'CC: ' + groups[ 1 ].length + ' ';
    }
    if ( groups[ 2 ].length > 0 ) {
        mailto = mailto + '&BCC=' + groups[ 2 ].join( ',' );
        tooltip = tooltip + 'BCC: ' + groups[ 2 ].length;
    }
    compose.href = mailto;
    compose.title = tooltip;
    compose.style.display = 'inline';
    if ( groups[ 0 ].length + groups[1].length + groups[2].length < 1 ) {
        initializeComposeList();
    }
}

function createXMLHttpRequest() 
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    return xmlHttp;
}

xmlHttp = createXMLHttpRequest();

function search( terms )
{
    initializeComposeList();

    xmlHttp.open( 'get', 'search.php?q=' + terms );
    xmlHttp.onreadystatechange = displayResults;
    xmlHttp.send( null );
}

function displayResults()
{
    if(xmlHttp.readyState==4)
    {
        // document.myForm.time.value=xmlHttp.responseText;
        document.getElementById( 'contact_list' ).innerHTML=xmlHttp.responseText;
    } 
}
